package validator

import (
	"fmt"
	"reflect"
	"strings"

	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"go.uber.org/zap"
)

// 定义一个全局翻译器
var Trans ut.Translator

// InitTrans 初始化翻译器
func InitTrans(locale string) {
	var err error
	// 修改gin框架中的validator引擎属性，实现自定义
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})

		zhT := zh.New() //中文翻译
		enT := en.New() //英文翻译器

		//第一个参数是备用（fallback）的语言环境
		//后面的参数是应该支持的语言环境（支持多个）
		// uni := ut.New(zhT,zhT)也是可以的
		uni := ut.New(enT, zhT, enT)
		//locale 通常取决于http请求头的 'accept-language'
		var ok bool
		Trans, ok = uni.GetTranslator(locale)
		if !ok {
			//return fmt.Errorf("uni.GetTranslate(%s) failed", locale)
			zap.L().Error("GetTranslator出错了", zap.Error(fmt.Errorf("uni.GetTranslate(%s) failed", locale)))
		}
		//注册翻译器

		switch locale {
		case "en":
			err = enTranslations.RegisterDefaultTranslations(v, Trans)
		case "zh":
			err = zhTranslations.RegisterDefaultTranslations(v, Trans)
		default:
			err = enTranslations.RegisterDefaultTranslations(v, Trans)
		}

		if err != nil {
			zap.L().Error("InitTrans出错了", zap.Error(err))
			panic(err)

		}
	}

}
